package jason.test.dirtest;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Handler;
import android.util.Log;

public class DirSensor implements SensorEventListener {
	Vector3 accData;
	Vector3 magData;
	Handler handler;
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		Vector3 data = new Vector3(event.values);
		Log.i("DirSensor", "onSensorChanged:"+data+"TYPE:"+event.sensor.getName());
		switch (event.sensor.getType()){
		case Sensor.TYPE_ACCELEROMETER :{
			accData = data;
			break;
		}
		case Sensor.TYPE_MAGNETIC_FIELD :{
			magData = data;
			break;
		}
		default : Log.w("onSensorChanged", "Unknown Sensor Type:"+event.sensor.getName());
		}
		if (handler != null)
			handler.sendEmptyMessage(1);
	}

	public Vector3 getAngleOfView(){
		//up towards the sky;
		Vector3 up = accData.copy();
		up.normolize();
		//north along the ground
		Vector3 north = magData.copy();
		north.normolize();
		north.add(up.copy().scale(-north.scalorProduct(up)));
		north.normolize();
		//east along the ground
		Vector3 east = north.vectorProduct(up);
		east.normolize();
		
		//calculate "down(0,0,-1)" z in <east,north,up> 
		Vector3 viewAngle = new Vector3(0,0,-1);
		viewAngle.rotate(east, north, up);				
				
		return viewAngle;
	}
	
	public String getDataDescription(){
		return "Accelerator:\n"+accData
				+"\nMagnetic:\n"+magData;
	}
	
	public void setHandler(Handler handler){
		this.handler = handler;
	}
	
	public void unsetHandler(){
		this.handler = null;
	}
}
